<template>
  <div class="body">
    <el-container style="display: flex; justify-content: center; align-items: center; height: 100vh;">
      <div class="main">
        <el-card class="box-card" shadow="hover">
          <div class="clearfix">
            <span>比赛信息添加</span>
          </div>
          <div class="form-container">
            <el-form :model="eventForm" label-width="120px" class="event-form">
              <el-form-item label="赛事名称">
                <el-input v-model="resetForm.eventName"></el-input>
              </el-form-item>
              <el-form-item label="报名截止时间">
                <el-date-picker v-model="resetForm.registrationDeadline" type="date"
                  placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="添加项目">
                <div class="custom-group-input-container">
                  <el-button type="primary" size="small" @click="dialogVisibleproject = true"
                    class="custom-button">+
                    添加项目</el-button>
                </div>
                <div class="custom-group-tags-container">
                  <el-tag v-for="project in eventForm.projects" :key="project.projectName" closable
                    @close="removeProject(project)" style="font-size: 15px;">
                    {{ project.projectName }}
                  </el-tag>
                </div>
                <el-dialog title="添加比赛项目" v-model="dialogVisibleproject" width="30%">
                  <el-form :model="form">
                    <el-form-item label="项目名称" label-width="120px">
                      <el-input v-model="newProject.projectName" autocomplete="off"></el-input>
                    </el-form-item>
                  </el-form>
                  <template #footer>
                    <el-button @click="dialogVisibleproject = false">取消</el-button>
                    <el-button type="primary" @click="submitFormproject">提交</el-button>
                  </template>
                </el-dialog>
              </el-form-item>
              <el-form-item label="添加组别">
                <div class="custom-group-input-container">
                  <el-button type="primary" size="small" @click="dialogVisible = true" class="custom-button">+
                    添加组别</el-button>
                </div>
                <div class="custom-group-tags-container">
                  <el-tag v-for="group in eventForm.groups" :key="group.groupname" closable @close="removeGroup(group)"
                    style="font-size: 15px;">
                    {{ group.groupname }}
                  </el-tag>
                </div>
                <el-dialog title="添加组别" v-model="dialogVisible" width="30%">
                  <el-form :model="newGroup">
                    <el-form-item label="组别名称" label-width="120px">
                      <el-input v-model="newGroup.groupname" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="参赛性别" label-width="120px">
                      <el-radio-group v-model="newGroup.sex">
                        <el-radio :value="1" size="large">男</el-radio>
                        <el-radio :value="0" size="large">女</el-radio>
                        <el-radio :value="2" size="large">不限</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="最大年龄" label-width="120px">
                      <el-input v-model="newGroup.maxAge" autocomplete="off" type="number"
                        @input="calculateBirthDates"></el-input>
                    </el-form-item>
                    <el-form-item label="最小年龄" label-width="120px">
                      <el-input v-model="newGroup.minAge" autocomplete="off" type="number"
                        @input="calculateBirthDates"></el-input>
                    </el-form-item>
                    <el-form-item label="最小出生日期" label-width="120px">
                      <el-date-picker v-model="newGroup.minBirthDay" type="date" placeholder="选择日期"
                        disabled></el-date-picker>
                    </el-form-item>
                    <el-form-item label="最大出生日期" label-width="120px">
                      <el-date-picker v-model="newGroup.maxBirthDay" type="date" placeholder="选择日期"
                        disabled></el-date-picker>
                    </el-form-item>
                  </el-form>
                  <template #footer>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitFormCategory">提交</el-button>
                  </template>
                </el-dialog>
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="resetForm.contactPhone"></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="resetForm.remarks"></el-input>
              </el-form-item>
              <el-form-item>
                <el-upload class="upload-drag" action="https://jsonplaceholder.typicode.com/posts/" multiple>
                  <el-button size="small" type="primary"
                  style="background-color: white;border: none; border-radius: 4px; padding: 10px 20px; font-size: 16px; font-weight: bold; margin-bottom: 10px; height: 40px;">
                    <Upload />
                  </el-button>
                  <div class="el-upload__tip">可上传多个文件</div>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="custom-button-end" @click="submitFormtitle">添加</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-container>
  </div>
</template>

<script setup>
import { getMatches } from '../js/api'; // 导入获取比赛列表的函数
import { ref, computed } from 'vue';
import axios from 'axios'; // 导入 axios
import { useRouter } from 'vue-router'; // 导入路由

const router = useRouter();

const competitions = ref([]);// 比赛列表

//页面数据初始化
const eventForm = ref({
  projects: [],
  groups: []
});

const dialogVisible = ref(false); // 控制添加组别对话框的显示与隐藏

const dialogVisibleproject = ref(false);

const token = localStorage.getItem('adminToken'); // 从 localStorage 获取 token

const Itemdisplay = ref(true)

const newProject = ref({ projectName: '' });

const newGroup = ref({ groupname: '', minAge: '', maxAge: '', minBirthDay: '', sex: '', maxBirthDay: '' });

//删除项目在页面停留的数据
const removeProject = (project) => {
  const index = eventForm.value.projects.indexOf(project);
  if (index !== -1) {
    eventForm.value.projects.splice(index, 1);
  }
};


//删除组别在页面停留的数据
const removeGroup = (group) => {
  const index = eventForm.value.groups.indexOf(group);
  if (index !== -1) {
    eventForm.value.groups.splice(index, 1);
  }
};

// 添加组别的数据
const form = ref({
  name: '',
  maxAge: '',
  minAge: '',
  sex: '',
  minBirthDay: '',
  maxBirthDay: ''
});

// 计算出生日期
const calculateBirthDates = () => {
  const today = new Date();
  const minAge = parseInt(newGroup.value.minAge, 10) || 0;
  const maxAge = parseInt(newGroup.value.maxAge, 10) || 0;

  // 计算最小出生日期
  const minBirthDate = new Date(today.getFullYear() - minAge, today.getMonth(), today.getDate());
  newGroup.value.minBirthDay = minBirthDate.toISOString().split('T')[0];

  // 计算最大出生日期
  const maxBirthDate = new Date(today.getFullYear() - maxAge, today.getMonth(), today.getDate());
  newGroup.value.maxBirthDay = maxBirthDate.toISOString().split('T')[0];
};

// 添加组别
const submitFormCategory = async () => {
  // 验证表单数据是否完整
  if (!newGroup.value.groupname  || !newGroup.value.minAge || !newGroup.value.maxAge) {
    ElMessage.error('请填写完整信息');
    return;
  }
  // 验证最小出生日期是否小于最大出生日期
  if ( newGroup.value.minAge >= newGroup.value.maxAge) {
    ElMessage.error('最小出生日期必须小于最大出生日期');
    newGroup.value = { groupname: '', minAge: '', maxAge: '', minBirthDay: '', sex: '', maxBirthDay: '' }; // 清空输入
    return;
  }

  if (newGroup.value.groupname.trim() && newGroup.value.minAge && newGroup.value.maxAge && new Date(newGroup.value.minBirthDay) && new Date(newGroup.value.maxBirthDay)) {
    eventForm.value.groups.push({ ...newGroup.value });
    newGroup.value = { groupname: '', minAge: '', maxAge: '', minBirthDay: '', sex: '', maxBirthDay: '' }; // 清空输入
  }
  dialogVisible.value = false; // 确保对话框在所有情况下都关闭
};

// 添加项目的数据
const formproject = ref({
  eventName: '',
  teamSize: '',
});

// 添加项目页面渲染按钮
const submitFormproject = async () => {
  if (!newProject.value.projectName ) {
    ElMessage.error('请填写完整信息');
    return;
  }
  if (newProject.value.projectName.trim()) {
    eventForm.value.projects.push({ ...newProject.value });
    newProject.value = { projectName: '' }; // 清空输入
  }
  dialogVisibleproject.value = false;
};
// 赛事添加的数据
const resetForm = ref({
  eventName: '',
  registrationDeadline: '',
  contactPhone: '',
  remarks: '',
  disabled: ''
})

// 计算当天日期
const currentDate = computed(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // getMonth() 返回的月份是从0开始的，所以需要+1
  const day = date.getDate();

  return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
});

// 判断手机号
function isValidPhoneNumber(phoneNumber) {
  const regex = /^\d{11}$/;
  return regex.test(phoneNumber);
}

// 添加赛事
const submitFormtitle = async () => {
  const isValid = await validateForm(resetForm.value);
  if (!isValid) return;

  const userDatatitle = prepareUserData(resetForm.value);

  try {
    const matchResponse = await addMatch(userDatatitle);
    if (!matchResponse.success) {
      handleMatchError(matchResponse);
      return;
    }

    const newMatchId = matchResponse.match.id;
    const newProjects = prepareProjects(eventForm.value.projects, newMatchId);
    const newGroups = prepareGroups(eventForm.value.groups, newMatchId);

    try {
      const projectsResponse = await addProjects(newProjects);
      if (!projectsResponse.success) {
        handleProjectsError(projectsResponse);
        return;
      }

      const groupsResponse = await addGroups(newGroups);
      if (!groupsResponse.success) {
        handleGroupsError(groupsResponse);
        return;
      }

      ElMessage.success('比赛、项目和组别添加成功');
    } catch (error) {
      handleAxiosError(error);
    }
  } catch (error) {
    handleAxiosError(error);
  }
};

// 验证表单  
const validateForm = async (formData) => {
  const today = new Date().toISOString().split('T')[0];
  const deadline = new Date(formData.registrationDeadline).toISOString().split('T')[0];

  if (today > deadline) {
    ElMessage.error('报名截止日期不能早于当前日期');
    return false;
  }

  if (!isValidPhoneNumber(formData.contactPhone)) {
    ElMessage.error('请输入12位数字的手机号');
    return false;
  }

  if (!formData.eventName || !formData.registrationDeadline || !formData.contactPhone) {
    ElMessage.error('请填写完整信息');
    return false;
  }

  return true;
};

// 准备用户数据  
const prepareUserData = (formData) => {
  formData.disabled = formData.disabled || 0;
  return {
    title: formData.eventName,
    deadline: formData.registrationDeadline,
    telephone: formData.contactPhone,
    mem: formData.remarks,
    disabled: formData.disabled,
  };
};

// 添加比赛  
const addMatch = async (userData) => {  
  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/match/add', userData, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    return response.data;
  } catch (error) {
    ElMessage.error(`添加比赛时出错: ${error.message}`);
    throw error;
  }
};

// 处理比赛错误  
const handleMatchError = (response) => {
  if (response.status === 500) {
    ElMessage.error('检查是否重名，请提供不同的组名称或服务器错误');
  } else {
    ElMessage.error('添加比赛失败');
  }
};

// 准备项目数据  
const prepareProjects = (projects, matchId) => {
  return projects.map(project => ({ ...project, matchId }));
};

// 添加项目  
const addProjects = async (projects) => {
  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/project/add', projects, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
    });
    return response.data;
  } catch (error) {
    throw error;
  }
};

// 处理项目错误  
const handleProjectsError = (response) => {
  if (response.status === 400) {
    ElMessage.error('项目名重复，换一个试试吧');
  } else if (response.status === 401) {
    ElMessage.error('令牌失效或已过期，请重新登录');
  } else if (response.status === 500) {
    ElMessage.error('检查是否重名，请提供不同的组名称或服务器错误');
  } else {
    ElMessage.error('添加项目失败');
  }
};

// 准备组别数据  
const prepareGroups = (groups, matchId) => {
  return groups.map(group => ({
    groupname: group.groupname,
    minBirthDay: new Date(group.minBirthDay),
    maxBirthDay: new Date(group.maxBirthDay),
    sex: group.sex,
    matchId,
  }));
};

// 添加组别  
const addGroups = async (groups) => {  
  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/matchgroup/add', groups, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    return response.data;
  } catch (error) {
    throw error;
  }
};

// 处理组别错误  
const handleGroupsError = (response) => {
  if (response.status === 400) {
    ElMessage.error('存在重复的matchId和groupname，请提供不同的组名称。');
  } else if (response.status === 500) {
    ElMessage.error('检查是否重名，请提供不同的组名称或服务器错误');
  } else {
    ElMessage.error('添加组别失败');
  }
};

// 处理 Axios 错误  
const handleAxiosError = (error) => {
  if (error.response) {
    ElMessage.error(`错误状态码: ${error.response.status}, 错误信息: ${error.response.data.msg || error.message}`);
  } else {
    ElMessage.error('请求失败，请检查网络连接');
  }
};

// 获取比赛列表
onMounted(async () => {
  try {
    const data = await getMatches();
    competitions.value = data.matches; // 将比赛列表赋值给 competitions
  } catch (err) {
    error.value = err.message;
  }
});
</script>

<style scoped>
.body {
  margin-top: 50px;
}

.event-form .el-form-item__label {
  color: black;
}

/* 为输入框、下拉框等设置灰色背景 */
.event-form .el-input__inner,
.event-form .el-select .el-input__inner,
.event-form .el-textarea__inner,
.event-form .el-date-editor .el-input__inner {
  background-color: #f5f5f5;
  color: black;
}

/* 自定义按钮样式 */
.custom-button {
  background-color: black;
  color: white;
}

/* 为标签设置灰色背景和黑色字体 */
.event-form .el-tag {
  background-color: #f5f5f5;
  color: black;
}

/* 设置卡片背景色 */
.box-card {
padding: 20px;
  border-radius:10px;
  background-color: #aacec6;
  width: 500px;
}
.main{
  display: flex;
  justify-content: center;
  align-items: center;
} 
span {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28px;
  text-align: center;
  margin-bottom: 20px;
}

svg {
  height: 40px;
  color: black;
}

.custom-button-end {
  position: relative;
  /* right: 30px; */
  width: 400px;
  background-color: black;
}

.custom-group-input-container {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  /* 添加一些间隔 */
}

.custom-group-tags-container {
  display: flex;
  flex-wrap: wrap;
}
</style>